/*
 * Copyright (c) 2000-2005 Apple Computer, Inc. All rights reserved.
 *
 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. The rights granted to you under the License
 * may not be used to create, or enable the creation or redistribution of,
 * unlawful or unlicensed copies of an Apple operating system, or to
 * circumvent, violate, or enable the circumvention or violation of, any
 * terms of an Apple operating system software license agreement.
 * 
 * Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
 */
/* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
/*
 * Copyright (c) 1989, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Rick Macklem at The University of Guelph.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */
/*
 * This file includes modifications of code found in the Apple XNU Kernel
 * and has been modifed for use in this Kext by Rick Macklem, May 2006.
 */


#ifndef APPLEKEXT
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/proc.h>
#include <sys/kauth.h>
#include <sys/mount_internal.h>
#include <sys/vnode.h>
#include <sys/ubc.h>
#include <sys/malloc.h>

#include <newnfs/nfs/nfsport.h>
#include <newnfs/nfsclient/nfsnode.h>
#include <newnfs/nfsclient/nfsmount.h>
#include <newnfs/nfsclient/nfsclient_var.h>

extern vnop_t **newnfs_vnodeop_p;
extern vnop_t **spec_newnfsnodeop_p;
extern vnop_t **fifo_newnfsnodeop_p;
u_long newnfsnodehash;

LIST_HEAD(nfsnodehashhead, nfsnode) *newnfsnodehashtbl;

lck_grp_t * ncl_node_hash_lck_grp;
lck_grp_attr_t * ncl_node_hash_lck_grp_attr;
lck_attr_t * ncl_node_hash_lck_attr;
lck_mtx_t *ncl_node_hash_mutex;
#endif	/* !APPLEKEXT */

/*
 * Initialize hash links for nfsnodes
 * and build nfsnode free list.
 */
APPLESTATIC void
ncl_nhinit(void)
{
	newnfsnodehashtbl = hashinit(desiredvnodes, M_NFSNODE, &newnfsnodehash);

	ncl_node_hash_lck_grp_attr = lck_grp_attr_alloc_init();
	ncl_node_hash_lck_grp = lck_grp_alloc_init("ncl_node_hash", ncl_node_hash_lck_grp_attr);

	ncl_node_hash_lck_attr = lck_attr_alloc_init();

	ncl_node_hash_mutex = lck_mtx_alloc_init(ncl_node_hash_lck_grp, ncl_node_hash_lck_attr);
}

/*
 * Look up a vnode/nfsnode by file handle.
 * Callers must check for mount points!!
 * In all cases, a pointer to a
 * nfsnode structure is returned.
 */
APPLESTATIC int
ncl_nget(
	mount_t mntp,
	vnode_t dvp,
	struct componentname *cnp,
	u_char *fhp,
	int fhsize,
	struct nfsvattr *nvap,
	u_int64_t *xidp,
	int flags,
	struct nfsnode **npp)
{
	struct nfsnode *np;
	struct nfsnodehashhead *nhpp;
	vnode_t vp, nvp;
	int error;
	mount_t mp;
	struct vnode_fsparam vfsp;
	uint32_t vid;

	/* Check for unmount in progress */
	if (!mntp || (mntp->mnt_kern_flag & MNTK_UNMOUNT)) {
		*npp = 0;
		return (!mntp ? ENXIO : EPERM);
	}

	nhpp = NFSNOHASH(ncl_hash(fhp, fhsize));
loop:
	lck_mtx_lock(ncl_node_hash_mutex);
	for (np = nhpp->lh_first; np != 0; np = np->n_hash.le_next) {
		mp = (np->n_flag & NINIT) ? np->n_mount : vnode_mount(NFSTOV(np));
		if (mntp != mp || np->n_fhp->nfh_len != fhsize ||
		    bcmp(fhp, np->n_fhp->nfh_fh, fhsize))
			continue;
		/* if the node is still being initialized, sleep on it */
		if (np->n_flag & NINIT) {
			OSBitOrAtomic((u_int32_t)NWINIT, (UInt32 *)&np->n_flag);
			msleep(np, ncl_node_hash_mutex, PDROP | PINOD, "ncl_nget", 0);
			goto loop;
		}
		vp = NFSTOV(np);
		vid = vnode_vid(vp);
		lck_mtx_unlock(ncl_node_hash_mutex);
		if ((error = vnode_getwithvid(vp, vid))) {
			/*
			 * If vnode is being reclaimed or has already
			 * changed identity, no need to wait.
			 */
			return (error);
		} 
		/* update attributes */
		error = nfscl_loadattrcache(np, nvap, NULL, xidp, 0);
		if (error) {
			vnode_put(vp);
		} else {
			if (dvp && cnp && (flags & NG_MAKEENTRY))
				cache_enter(dvp, vp, cnp);
			*npp = np;
		}
		return(error);
	}

	/*
	 * allocate and initialize nfsnode and stick it in the hash
	 * before calling getnewvnode().  Anyone finding it in the
	 * hash before initialization is complete will wait for it.
	 */
	MALLOC_ZONE(np, struct nfsnode *, sizeof *np, M_NFSNODE, M_WAITOK);
	if (!np) {
		lck_mtx_unlock(ncl_node_hash_mutex);
		*npp = 0;
		return (ENOMEM);
	}
	bzero((caddr_t)np, sizeof *np);
	np->n_flag |= NINIT;
	np->n_mount = mntp;

	/* setup node's file handle */
	MALLOC(np->n_fhp, struct nfsfh *, sizeof (struct nfsfh) + fhsize,
	    M_NFSFH, M_WAITOK);
	if (np->n_fhp == NULL) {
		lck_mtx_unlock(ncl_node_hash_mutex);
		FREE_ZONE(np, sizeof *np, M_NFSNODE);
		*npp = NULL;
		return (ENOMEM);
	}
	bcopy(fhp, np->n_fhp->nfh_fh, fhsize);
	np->n_fhp->nfh_len = fhsize;

	/* Insert the nfsnode in the hash queue for its new file handle */
	np->n_flag |= NHASHED;
	LIST_INSERT_HEAD(nhpp, np, n_hash);

	/* release lock on hash table */
	lck_mtx_unlock(ncl_node_hash_mutex);

	/* do initial loading of attributes */
	error = nfscl_loadattrcache(np, nvap, NULL, xidp, 1);
	if (error) {
		lck_mtx_lock(ncl_node_hash_mutex);
		LIST_REMOVE(np, n_hash);
		OSBitAndAtomic((int32_t)~(NHASHED | NINIT), (UInt32 *)&np->n_flag);
		if (np->n_flag & NWINIT) {
			OSBitAndAtomic((int32_t)~NWINIT, (UInt32 *)&np->n_flag);
			wakeup((caddr_t)np);
		}
		lck_mtx_unlock(ncl_node_hash_mutex);
		FREE((caddr_t)np->n_fhp, M_NFSFH);
		FREE_ZONE(np, sizeof *np, M_NFSNODE);
		*npp = NULL;
		return (error);
	}
	np->n_mtime = nvap->na_mtime;
	if (nvap->na_type == VDIR)
		np->n_ncmtime = nvap->na_mtime;
	NMODEINVALIDATE(np);

	/* now, attempt to get a new vnode */
	vfsp.vnfs_mp = mntp;
	vfsp.vnfs_vtype = nvap->na_type;
	vfsp.vnfs_str = "newnfs";
	vfsp.vnfs_dvp = dvp;
	vfsp.vnfs_fsnode = np;
	if (nvap->na_type == VFIFO)
		vfsp.vnfs_vops = fifo_newnfsnodeop_p;
	else if (nvap->na_type == VBLK || nvap->na_type == VCHR)
		vfsp.vnfs_vops = spec_newnfsnodeop_p;
	else
		vfsp.vnfs_vops = newnfs_vnodeop_p;
	vfsp.vnfs_markroot = (flags & NG_MARKROOT) ? 1 : 0;
	vfsp.vnfs_marksystem = 0;
	vfsp.vnfs_rdev = 0;
	vfsp.vnfs_filesize = nvap->na_size;
	vfsp.vnfs_cnp = cnp;
	if (dvp && cnp && (flags & NG_MAKEENTRY))
		vfsp.vnfs_flags = 0;
	else
		vfsp.vnfs_flags = VNFS_NOCACHE;
	error = vnode_create(VNCREATE_FLAVOR, VCREATESIZE, &vfsp, &nvp);
	if (error) {
		lck_mtx_lock(ncl_node_hash_mutex);
		LIST_REMOVE(np, n_hash);
		OSBitAndAtomic((int32_t)~(NHASHED | NINIT), (UInt32 *)&np->n_flag);
		if (np->n_flag & NWINIT) {
			OSBitAndAtomic((int32_t)~NWINIT, (UInt32 *)&np->n_flag);
			wakeup((caddr_t)np);
		}
		lck_mtx_unlock(ncl_node_hash_mutex);
		FREE((caddr_t)np->n_fhp, M_NFSFH);
		FREE_ZONE(np, sizeof *np, M_NFSNODE);
		*npp = NULL;
		return (error);
	}
	vp = nvp;
	np->n_vnode = vp;
	vnode_addfsref(vp);
	vnode_settag(vp, VT_NEWNFS); // XXX shouldn't this be a vnode_create() parameter?
	*npp = np;
	/* node is now initialized */

	/* check if anyone's waiting on this node */
	lck_mtx_lock(ncl_node_hash_mutex);
	OSBitAndAtomic((int32_t)~NINIT, (UInt32 *)&np->n_flag);
	if (np->n_flag & NWINIT) {
		OSBitAndAtomic((int32_t)~NWINIT, (UInt32 *)&np->n_flag);
		wakeup((caddr_t)np);
	}
	lck_mtx_unlock(ncl_node_hash_mutex);

	return (error);
}


APPLESTATIC int
ncl_inactive(ap)
	struct vnop_inactive_args /* {
		struct vnodeop_desc *a_desc;
		vnode_t a_vp;
		vfs_context_t a_context;
	} */ *ap;
{
	register struct nfsnode *np;
	register struct sillyrename *sp;
	vnode_t vp;

	vp = ap->a_vp;
	np = VTONFS(vp);
	if (NFS_ISV4(vp) && vnode_vtype(vp) == VREG) {
		/*
		 * Since mmap()'d files do I/O after VOP_CLOSE(), the NFSv4
		 * Close operations are delayed until now. Any dirty buffers
		 * must be flushed before the close, so that the stateid is
		 * available for the writes.
		 */
		if (nfscl_mustflush(vp))
			(void) ncl_flush(vp, MNT_WAIT, NULL,
			    vfs_context_proc(ap->a_context), 1);
		(void) nfsrpc_close(vp, 1, vfs_context_proc(ap->a_context));
	}

	if (vnode_vtype(vp) != VDIR) {
		sp = np->n_sillyrename;
		np->n_sillyrename = (struct sillyrename *)0;
	} else
		sp = (struct sillyrename *)0;

	if (sp) {
		/*
		 * Remove the silly file that was rename'd earlier
		 */
#if DIAGNOSTIC
		kprintf("ncl_inactive removing %s, dvp=%x, a_vp=%x, ap=%x, np=%x, sp=%x\n",
			&sp->s_name[0], (unsigned)sp->s_dvp, (unsigned)vp, (unsigned)ap,
			(unsigned)np, (unsigned)sp);
#endif
		ncl_vinvalbuf(vp, 0, sp->s_cred, vfs_context_proc(ap->a_context), 1);
		np->n_size = 0;
		ubc_setsize(vp, (off_t)0);
		ncl_removeit(sp, vp);
		/*
		 * remove nfsnode from hash now so we can't accidentally find it
		 * again if another object gets created with the same filehandle
		 * before this vnode gets reclaimed
		 */
		lck_mtx_lock(ncl_node_hash_mutex);
		LIST_REMOVE(np, n_hash);
		OSBitAndAtomic((int32_t)~NHASHED, (UInt32 *)&np->n_flag);
		lck_mtx_unlock(ncl_node_hash_mutex);
		if (IS_VALID_CRED(sp->s_cred))
			kauth_cred_unref(&sp->s_cred);
		vnode_rele(sp->s_dvp);
		FREE_ZONE((caddr_t)sp, sizeof (struct sillyrename), M_NFSREQ);
		vnode_recycle(vp);
	}
	/* clear all flags other than these */
	OSBitAndAtomic((UInt32)(NMODIFIED | NFLUSHINPROG | NFLUSHWANT | NHASHED), (UInt32 *)&np->n_flag);
	return (0);
}

/*
 * Reclaim an nfsnode so that it can be used for other purposes.
 */
APPLESTATIC int
ncl_reclaim(ap)
	struct vnop_reclaim_args /* {
		struct vnodeop_desc *a_desc;
		vnode_t a_vp;
		vfs_context_t a_context;
	} */ *ap;
{
	vnode_t vp = ap->a_vp;
	struct nfsnode *np = VTONFS(vp);
	struct nfsdmap *dp, *dp2;
	kauth_cred_t cred;
	proc_t p;

	p = vfs_context_proc(ap->a_context);
	cred = vfs_context_ucred(ap->a_context);

	vnode_removefsref(vp);

	if (np->n_flag & NHASHED) {
		lck_mtx_lock(ncl_node_hash_mutex);
		LIST_REMOVE(np, n_hash);
		OSBitAndAtomic((int32_t)~NHASHED, (UInt32 *)&np->n_flag);
		lck_mtx_unlock(ncl_node_hash_mutex);
	}

	/*
	 * Call nfscl_reclaimnode() to save attributes in the delegation,
	 * as required.
	 */
	if (vp->v_type == VREG)
		nfscl_reclaimnode(vp);

	/*
	 * Since vclean() doesn't do an ncl_vinvalbuf() for me, I had better
	 * do it here. If I find any dirty buffers, I need to panic.
	 */
	(void) ncl_vinvalbuf(vp, V_SAVE, cred, p, 0);
	if (!LIST_EMPTY(&np->n_dirtyblkhd))
		panic("nclreclaim");

	/*
	 * Free up any directory cookie structures and
	 * large file handle structures that might be associated with
	 * this nfs node.
	 */
	if (vnode_vtype(vp) == VDIR) {
		dp = np->n_cookies.lh_first;
		while (dp) {
			dp2 = dp;
			dp = dp->ndm_list.le_next;
			FREE_ZONE((caddr_t)dp2,
					sizeof (struct nfsdmap), M_NFSDIROFF);
		}
	}
	if (np->n_v4 != NULL)
		FREE((caddr_t)np->n_v4, M_NFSV4NODE);
	FREE((caddr_t)np->n_fhp, M_NFSFH);
	vnode_clearfsnode(vp);

	FREE_ZONE(np, sizeof(struct nfsnode), M_NFSNODE);
	return (0);
}

